package jp.co.sharp.android.parents.kidsguard.activity.setting;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.bluetooth.parentble.ParentBleTransfer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.adapter.OkaeriSettingItemAdaptor;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.dto.DeviceListDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;

public class OkaeriSettingActivity extends AppCompatActivity {
    public ParentBleTransfer mParentBleTransfer;
    private DealWithWaitingDlg mDealWithWaitingDlg;
    private App mApp;


    List<DeviceListDto> mDeviceLists;
    ListView mListView;
    OkaeriSettingItemAdaptor mAdaptor;

    private KidInfoEntity mKidInfoEntity;
    private int mViewProcess = 0;
    private boolean mScreenOperate = false;

    private boolean mUnReceiver = true;
    private static final String TAG = "TAG";

    // ページジャンプ
    public static boolean mPageJumpFlag = false;
    // システムホームプレス
    private boolean mSystemHomeFlag = false;
    private final static int SUCCESS_CODE = 200;
    private final static int DEVICE_SELECTOR_REQUEST_CODE = 1;
    // プログラムロック
    private String mSyncLock = "syncLock";
    private JSONObject mJsonObj;
    // 編集を再開しています...
    private boolean mEditReopening = false;
    private static final int PAGE_EDIT_REOPEN = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(this.TAG, "OkaeriSettingActivity_onCreate");
        setContentView(R.layout.activity_okaeri_setting);

        getIntentFromOkaeriNotification();
        mApp = (App) getApplication();
        initReceiver();
        initListener();
        mListView = findViewById(R.id.deviceList);
        try {
            initDeviceList();
        } catch (Exception e) {
           Log.e(TAG,e.getMessage());
        }

//        // 検索中...
//        String pDlgMsg = "キッズケータイから情報を取得しています...";
//        mDealWithWaitingDlg = new DealWithWaitingDlg(OkaeriSettingActivity.this, R.style.dealWithWaitingDlg, pDlgMsg, true);
//        mDealWithWaitingDlg.show();
//        new BusinessThread(Constants.SEND_KID_GET_INFO, mParentBleTransfer, mKidInfoEntity, getInitData(), PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION).start();
    }

    public void getIntentFromOkaeriNotification(){
        try {
            Intent intent = getIntent();
            String jsonObjStr = intent.getStringExtra("jsonObject");
            mJsonObj = new JSONObject(jsonObjStr);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "PowerSettingActivity_onRestart");
        synchronized (mSyncLock) {
            if (mSystemHomeFlag) {
                if (mApp.getAppStatus() != Constants.APP_STATUS_USER_PRESENT) {
                    Message msg = new Message();
                    msg.what = PAGE_EDIT_REOPEN;
                    handler.sendMessage(msg);
                }
                mSystemHomeFlag = false;
            }
        }

    }

    @Override
    protected void onStop() {
        Log.i(this.TAG, "OkaeriSettingActivity_onStop");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        Log.i(this.TAG, "OkaeriSettingActivity_onDestroy");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(this.TAG, "OkaeriSettingActivity_onActivityResult");
        initReceiver();
        if (resultCode == SUCCESS_CODE) {
            if (requestCode == DEVICE_SELECTOR_REQUEST_CODE) {
                int position = data.getIntExtra("position", -1);
                String name = data.getStringExtra("name");

                mDeviceLists.get(position).setDeviceNickName(name);
                mDeviceLists.get(position).setDeviceType(1);
                mDeviceLists.get(position).setDeviceId(data.getStringExtra("id"));
                mAdaptor.notifyDataSetChanged();
            }
        }
    }

    /**
     * ページリターンキー、フルスクリーンリターンジェスチャー
     */
    @Override
    public void onBackPressed() {
        Log.i(TAG, "OkaeriSettingActivity_onBackPressed");
        backView();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "OkaeriSettingActivity_onStart");
        mApp.setAppStatus(Constants.APP_STATUS_INIT);
    }

    public void initListener() {
        Log.i(this.TAG, "OkaeriSettingActivity_backView");
        ImageView imageView = findViewById(R.id.backView);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                backView();
            }
        });
    }

    public void backView() {
        Log.i(this.TAG, "OkaeriSettingActivity_backView");
//        for (DeviceListDto device:mDeviceLists) {
//            if(device.getDeviceNickName().equals("おとうさん")){
//                mDeviceLists.remove(device);
//            }
//        }
        Iterator<DeviceListDto> iterator = mDeviceLists.iterator();
        while (iterator.hasNext()) {
            DeviceListDto deviceListDto = iterator.next();
//            if(null == deviceListDto.getDeviceId() || "".equals(deviceListDto.getDeviceId())){
//                iterator.remove();
//            }
            if(deviceListDto.getDeviceNickName().equals("おとうさん")){
                iterator.remove();
            }
        }
        Intent intent = new Intent();
        intent.putExtra("deviceList", mDeviceLists.toString());
        setResult(SUCCESS_CODE, intent);
        mPageJumpFlag=true;
        finish();
    }


    public void initReceiver() {
        Log.i(this.TAG, "OkaeriSettingActivity_initReceiver");

        mKidInfoEntity = ((App) getApplication()).findKidInfoBySelect();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        registerReceiver(receiver, filter);
        registerReceiver(systemReceiver, filter);
        this.mParentBleTransfer = ((App) getApplication()).getmParentBleTransfer();
        mUnReceiver = false;
    }


    public JSONObject getInitData() {
        Log.i(this.TAG, "OkaeriSettingActivity_getInitData");
        JSONObject jsonObject = new JSONObject();
        try {

            jsonObject.put("method", RequestMethodConstants.METHOD_GET_RETURN_SETTINGS);
            jsonObject.put("data", JSONObject.NULL);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
//            e.printStackTrace();
        }
        return jsonObject;
    }


    public void initDeviceList() throws Exception {
        Log.i(TAG, "OkaeriSettingActivity_initDeviceList");
        //get user
        TextView textView = findViewById(R.id.userName);
        textView.setText((mApp.findKidInfoBySelect().getKidName() + "のキッズケータイ"));
        if(null == mJsonObj){
            return;
        }
        mDeviceLists = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            DeviceListDto dto = new DeviceListDto();
            dto.setIndex(i);
            dto.setDeviceNickName("おとうさん");
            mDeviceLists.add(dto);
        }
        JSONArray array = mJsonObj.getJSONObject("data").getJSONArray("deviceList");
        if (array.length() > 0) {
            for (int i = 0; i < array.length(); i++) {
                JSONObject data = (JSONObject) array.get(i);
                int index = data.getInt("index");
                mDeviceLists.get(index).setDeviceId(data.getString("deviceId"));
                mDeviceLists.get(index).setDeviceName(data.getString("deviceName"));
                mDeviceLists.get(index).setDeviceNickName(data.getString("deviceNickName"));
                mDeviceLists.get(index).setDeviceType(data.getInt("deviceType"));
                mDeviceLists.get(index).setIndex(index);
            }
        }
        setAdaptor();
    }


    public void setAdaptor() {
        Log.i(TAG, "OkaeriSettingActivity_setAdaptor");
        mAdaptor = new OkaeriSettingItemAdaptor(OkaeriSettingActivity.this, R.layout.activity_okaeri_setting_item, mDeviceLists,
                new OkaeriSettingItemAdaptor.OnClickItemListenter() {
                    @Override
                    public void chooseItemClick(int position, View view) {

                    }
                });
        mListView.setAdapter(mAdaptor);
    }

    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_INIT);
                        mScreenOperate = true;
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT, PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION, mParentBleTransfer, mKidInfoEntity).start();
                    }

                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                        if (!mPageJumpFlag) {
                            Message msg = new Message();
                            msg.what = PAGE_EDIT_REOPEN;
                            handler.sendMessage(msg);
                        }
                    }
                } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_INIT);
                        mSystemHomeFlag = true;
                        mScreenOperate = true;
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT,
                                mParentBleTransfer,
                                mKidInfoEntity,
                                null,
                                PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION).start();
                    }

                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    // 初期化
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String macAddress = bluetoothReceiverDto.getAddress();
                    if (mApp.isMimamoriCheck(macAddress)) {
                        mApp.addmLsIsMimamori(macAddress);
                        // TODO Mimamori
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT,
                                mParentBleTransfer,
                                mKidInfoEntity,
                                null,
                                PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION).start();
                        // ページジャンプ
                        mPageJumpFlag = true;
                        Intent intent1 = new Intent();
                        intent1.setAction(Constants.ACTION_IS_MIMAMORI);
                        intent1.setClass(OkaeriSettingActivity.this, HomeActivity.class);
                        startActivity(intent1);
                    } else {
                        mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                        mApp.updateKidInfo(mKidInfoEntity);

                        String message = mKidInfoEntity.getKidName() + "と切断されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(OkaeriSettingActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                processWarringDlg.dismiss();
                                // ページジャンプ
                                mPageJumpFlag = true;
                                Intent intent1 = new Intent();
                                intent1.setClass(OkaeriSettingActivity.this, SettingActivity.class);
                                startActivity(intent1);
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };
    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "OkaeriSettingActivity_BroadcastReceiver");
            try {
                String action = intent.getAction();
                if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    if (bluetoothReceiverDto.isFinished()) {
                        switch (mViewProcess) {
                            case Constants.SEND_KID_ENTER:
                                mViewProcess = Constants.SEND_KID_GET_INFO;
                                if (!mScreenOperate) {
                                    new BusinessThread(Constants.SEND_KID_GET_INFO, mParentBleTransfer, mKidInfoEntity, getInitData(), PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION).start();
                                } else {
                                    mEditReopening = false;
                                    mScreenOperate = false;
                                    handler.sendEmptyMessage(0);
                                }
                                break;
                            case Constants.SEND_KID_EXIT:
                                if (mDealWithWaitingDlg != null && mDealWithWaitingDlg.isShowing()) {
                                    mDealWithWaitingDlg.dismiss();
                                }
                                if (!mScreenOperate) {
                                    // ページジャンプ
                                    mPageJumpFlag = true;
                                    OkaeriSettingActivity.this.finish();
                                }
                                break;
                        }
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String retStr = bluetoothReceiverDto.getRetStr();
                    JSONObject jsonObject = new JSONObject(retStr);

                   if (RequestMethodConstants.METHOD_GET_OPERATING_STATE.equals(jsonObject.getString("method"))) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        if (Constants.IS_USING_OK.equals(data.getString("state"))) {
                            //send enter
                            mViewProcess = Constants.SEND_KID_ENTER;
                            new BusinessThread(Constants.SEND_KID_ENTER, PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION, mParentBleTransfer, mKidInfoEntity).start();
                        } else {
                            mDealWithWaitingDlg.dismiss();
                            String message = "別のスマートフォンから操作中のため、設定を変更できません。";
                            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(OkaeriSettingActivity.this, R.style.commonDlg, message);
                            processWarringDlg.show();
                            processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                @Override
                                public void onOperateSet() {
                                    processWarringDlg.dismiss();
                                    OkaeriSettingActivity.this.finish();
                                }
                            });
                        }
                    } else if (RequestMethodConstants.METHOD_ON_SYNC_RESULT.equals(jsonObject.getString("method"))) {
                        if (Constants.ON_SYNC_RESULT.equals(jsonObject.getString("result"))) {
                            // ページジャンプ
                            mPageJumpFlag = true;
                            //c
                        }
                    } else if (RequestMethodConstants.METHOD_ON_OPERATE_INTERRUPT.equals(jsonObject.getString("method"))) {
                        String message = "キッズケータイが操作されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(OkaeriSettingActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                // ページジャンプ
                                mPageJumpFlag = true;
                                Intent intent = new Intent(OkaeriSettingActivity.this, SettingActivity.class);
                                Intent intent1 = new Intent(OkaeriSettingActivity.this,SettingActivity.class);
                                startActivity(intent1);
                                processWarringDlg.dismiss();
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
//                e.printStackTrace();
            }
        }
    };

    /**
     * Dialog閉じる
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                mDealWithWaitingDlg.dismiss();
            } else if (msg.what == PAGE_EDIT_REOPEN) {
                if (!mEditReopening) {
                    String message = "編集を再開しています...";
                    mDealWithWaitingDlg = new DealWithWaitingDlg(OkaeriSettingActivity.this, R.style.commonDlg, message, false);
                    mDealWithWaitingDlg.show();
                    mScreenOperate = true;
                    mViewProcess = Constants.SEND_KID_IS_USING;
                    new BusinessThread(Constants.SEND_KID_IS_USING,
                            mParentBleTransfer,
                            mKidInfoEntity,
                            null,
                            PageSerialNumConstants.PAGE_SERIAL_NUM_POWER_SETTING).start();
                    // ブロードキャストの再登録
                    unregisterReceiver(systemReceiver);
                    initReceiver();
                    mEditReopening = true;
                }
            }
        }
    };
}
